<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="color: red">* </span><span>指导教师</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['eqxm:teamTeacher:add']"
            :disabled="!disChanges()"
            >新增</el-button
          >
        </el-col>
      </el-row>

      <el-table
        border
        v-loading="loading"
        :data="teamTeacherList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="所在单位" align="center" prop="college" />
        <el-table-column label="工号" align="center" prop="username" />
        <el-table-column label="政治面貌" align="center" prop="outlook" />
        <el-table-column label="联系方式" align="center" prop="tel" />
        <el-table-column label="微信激活" align="center">
          <template slot-scope="scope">
            {{scope.row.isActivateWechatTeacher==1?"是":"否"}}
          </template>
        </el-table-column>
        <el-table-column label="是否跟队" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isheel == 0">是</span>
            <span v-if="scope.row.isheel == 1">否</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['eqxm:teamTeacher:remove']"
              :disabled="!disChanges()"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span style="color: red">* </span><span>团队成员</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="stuhandleAdd"
            v-hasPermi="['eqxm:teamStudent:add']"
            :disabled="!disChanges()"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table border v-loading="stuloading" :data="teamStudentList">
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="所在单位" align="center" prop="college" />
        <el-table-column label="学号" align="center" prop="username" />
        <el-table-column label="政治面貌" align="center" prop="outlook" />
        <el-table-column label="联系方式" align="center" prop="tel" />
        <el-table-column label="微信激活" align="center">
          <template slot-scope="scope">
            {{scope.row.isActivateWechatStu==1?"是":"否"}}
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">
            {{scope.row.role | teamStuRoleMap}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="stuhandleDelete(scope.row)"
              v-hasPermi="['eqxm:teamStudent:remove']"
              :disabled="!disChanges()"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="stutotal > 0"
        :total="stutotal"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改团队老师对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-select
            v-model="form.username"
            remote
            reserve-keyword
            filterable
            :remote-method="remoteTeacher"
            placeholder="请输入关键词"
            :loading="searchLoading"
          >
            <el-option
              v-for="(item, index) in teacherOptions"
              :key="index"
              :label="item.xh + '--' + item.xm"
              :value="item.xh"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="政治面貌" prop="outlook">
          <!-- <el-input v-model="form.outlook" placeholder="请输入政治面貌" />-->
          <el-select v-model="form.outlook" placeholder="请选择">
            <el-option label="中共党员" value="中共党员"></el-option>
            <el-option label="中共预备党员" value="中共预备党员"></el-option>
            <el-option label="共青团员" value="共青团员"></el-option>
            <el-option label="群众" value="群众"></el-option>
            <el-option label="其他民主党派" value="其他民主党派"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="是否跟队" prop="isheel">
          <el-select v-model="form.isheel" placeholder="请选择">
            <el-option label="是" value="0"></el-option>
            <el-option label="否" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改团队学生对话框 -->
    <el-dialog :title="stutitle" :visible.sync="stuopen" width="500px" append-to-body>
      <el-form ref="stuform" :model="stuform" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-select
            v-model="stuform.username"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteStudent"
            :loading="searchLoading"
          >
            <el-option
              v-for="(item, index) in studentOptions"
              :key="index"
              :label="item.xh + '--' + item.xm"
              :value="item.xh"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="政治面貌" prop="outlook">
          <el-select v-model="stuform.outlook" placeholder="请选择">
            <el-option label="中共党员" value="中共党员"></el-option>
            <el-option label="中共预备党员" value="中共预备党员"></el-option>
            <el-option label="共青团员" value="共青团员"></el-option>
            <el-option label="群众" value="群众"></el-option>
            <el-option label="其他民主党派" value="其他民主党派"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="stuform.tel" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="stuform.role" placeholder="请选择">
            <el-option label="负责人" value=1></el-option>
            <el-option label="宣传员" value=2></el-option>
            <el-option label="安全员" value=3></el-option>
            <el-option label="成员" value=4></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="stusubmitForm">确 定</el-button>
        <el-button @click="stucancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-button v-hasPermi="['eqxm:team:edit']" style="float: right" type="primary" @click="next"
      >下一步</el-button
    >
    <el-button
      v-hasPermi="['eqxm:team:edit']"
      style="float: right; margin-right: 10px"
      type="primary"
      @click="back"
      >上一步</el-button
    >
  </div>
</template>

<script>
import {
  listTeamTeacher,
  getTeamTeacher,
  delTeamTeacher,
  addTeamTeacher,
  updateTeamTeacher,
  exportTeamTeacher,
  canChooseList,
  canChooseStuList,
  canChooseTeacherList,
} from '@/api/eqxm/teamTeacher';
import CommonUtils from '@/utils/CommonUtils';
import {
  listTeamStudent,
  getTeamStudent,
  delTeamStudent,
  addTeamStudent,
  updateTeamStudent,
  exportTeamStudent,
} from '@/api/eqxm/teamStudent';
import { getTeam } from '@/api/eqxm/team';
import { teamStuRoleMap,teamStuRoleOptions } from '@/views/eqxm/enum';
import CKEditor from 'ckeditor4-vue';
import { mapGetters } from 'vuex';
export default {
  name: 'TeamTeacher',
  components: {
    ckeditor: CKEditor.component,
  },
  computed: {
    ...mapGetters(['roles', 'name']),
  },
  filters: {
    teamStuRoleMap: function (value) {
      return teamStuRoleMap.get(value);
    },
  },
  props:['isAdmin'],
  data() {
    return {
      // 遮罩层
      loading: true,
      stuloading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      stutotal: 0,
      // 团队老师表格数据
      teamTeacherList: [],
      teamStudentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      stuopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamid: null,
        name: null,
        college: null,
        username: null,
        outlook: null,
        tel: null,
        isheel: null,
      },
      // 表单参数
      form: {
        username: null,
        outlook: null,
        tel: null,
        isheel: null,
      },
      stuform: {
        username: null,
        outlook: null,
        tel: null,
        role: null,
      },
      // 表单校验
      rules: {
        username: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        outlook: [{ required: true, message: '政治面貌不能为空', trigger: 'blur' }],
        tel: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          // {
          //   pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          //   message: '请输入正确的手机号码',
          //   trigger: 'blur',
          // },
        ],
        isheel: [{ required: true, message: '是否跟队不能为空', trigger: 'blur' }],
        role: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
      },
      teamId: '',
      teacherOptions: [],
      studentOptions: [],
      canChange: null,
      stutitle: '',
      searchLoading: false,
      editorData: '',
      editorConfig: {
        // The configuration of the editor.
      },
      //团队总人数
      teamTotal: null,
      teamInfo:{}
    };
  },
  created() {
    this.getList();
    // canChooseList().then(response => {
    //   this.teacherOptions = response.teacher;
    //   //this.studentOptions=response.stu;
    //   console.log(response);
    // });
  },
  methods: {
    /** 查询团队老师列表 */
    getList() {
      const id = CommonUtils.getCurTeamInfo().id;
      this.teamId = id;
      this.queryParams.teamid = id;
      this.loading = true;
      getTeam(this.teamId).then(response => {
        this.teamInfo = response.data;
        console.log(response.data.createBy == this.name);
        this.canChange = response.data.createBy == this.name;
      });
      listTeamTeacher(this.queryParams).then(response => {
        this.teamTeacherList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listTeamStudent(this.queryParams).then(response => {
        this.teamStudentList = response.rows;
        this.stutotal = response.total;
        this.stuloading = false;
      });
      this.teamTotal = this.stutotal + this.total;
    },
    disChanges() {
      // return this.teamTeacherList[0].createBy==this.name
      // getTeam(this.teamId).then(response => {
      //   console.log(response.data.createBy==this.name)
      //   return response.data.createBy == this.name;
      // });
      var status =  this.teamInfo.status==0 ||  this.teamInfo.status==2 ||  this.teamInfo.status==3
      // console.log(this.canChange && status,"status")
      return this.isAdmin || this.canChange && status;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teamid: null,
        name: null,
        college: null,
        username: null,
        outlook: null,
        tel: null,
        isheel: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.teamTotal >= 60) {
        this.$modal.msgError('人数到达团队上限（60个）!');
      } else {
        console.log(this.editorData);
        this.reset();
        this.open = true;
        this.title = '添加团队老师';
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTeamTeacher(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改团队老师';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeamTeacher(this.form).then(response => {
              if (response.code==200) {
                this.$modal.msgSuccess('修改成功');
                this.open = false;
                this.getList();
              }
            });
          } else {
            this.form.teamid = this.teamId;
            addTeamTeacher(this.form).then(response => {
              console.log(response,"res")
              if (response.code==200) {
                this.$modal.msgSuccess('新增成功');
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除团队老师编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delTeamTeacher(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有团队老师数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportTeamTeacher(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    /** 删除按钮操作 */
    stuhandleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除团队学生编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delTeamStudent(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        });
    },
    /** 新增按钮操作 */
    stuhandleAdd() {
      if (this.teamTotal >= 60) {
        this.$modal.msgError('人数到达团队上限（60个）!');
      } else {
        this.stureset();
        this.stuopen = true;
        this.stutitle = '添加团队成员';
      }
    },
    // 表单重置
    stureset() {
      this.stuform = {
        id: null,
        teamid: null,
        name: null,
        college: null,
        username: null,
        outlook: null,
        tel: null,
        role: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm('stuform');
    },
    /** 提交按钮 */
    stusubmitForm() {
      this.$refs['stuform'].validate(valid => {
        if (valid) {
          if (this.stuform.id != null) {
            updateTeamStudent(this.stuform).then(response => {
              if (response.code==200) {
                this.$modal.msgSuccess('修改成功');
                this.stuopen = false;
                this.getList();
              }
            });
          } else {
            this.stuform.teamid = this.teamId;
            addTeamStudent(this.stuform).then(response => {
              if (response.code==200) {
                this.$modal.msgSuccess('新增成功');
                this.stuopen = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    // 取消按钮
    stucancel() {
      this.stuopen = false;
      this.stureset();
    },
    /** 查询学生 */
    remoteStudent(query) {
      if (query !== '') {
        this.searchLoading = true;
        canChooseStuList(query).then(response => {
          console.log(response);
          this.searchLoading = false;
          this.studentOptions = response.rows;
          // this.studentOptions = response.filter(item => {
          //   return item.xm.toLowerCase()
          //     .indexOf(query.toLowerCase()) > -1;
          // });
        });
      } else {
        this.options = [];
      }
    },
    /** 查询老师 */
    remoteTeacher(query) {
      if (query !== '') {
        this.searchLoading = true;
        canChooseTeacherList(query).then(response => {
          console.log(response);
          this.searchLoading = false;
          this.teacherOptions = response.rows;
        });
      } else {
        this.teacherOptions = [];
      }
    },
    onNamespaceLoaded(CKEDITOR) {
      console.log(666, CKEDITOR);
    },
    onEditorReady(editor) {
      this.ready(editor);
    },
    back() {
      this.$parent.jump(0);
    },
    next() {
       if(this.total<=0){
        this.$modal.msgError('团队指导老师不能为空！');
      }else{
        this.$parent.jump(2);
      }
    },
  },
};
</script>
